import { NextRequest, NextResponse } from "next/server";
import os from "os";
const convertToMB = (bytes: number, decimals = 2) => {
  if (bytes === 0) return "0 Bytes";

  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];

  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
};
function formatMemoryUsageInMB() {
  const memUsage = process.memoryUsage();

  return {
    arrbuffer: convertToMB(memUsage.arrayBuffers),
    rss: convertToMB(memUsage.rss), // 整个程序实际占用的操作系统内存，包括代码，数据，共享库等
    heapTotal: convertToMB(memUsage.heapTotal), // JS 对象，数组等 Nodejs 动态分配的内存区域占用
    heapUsed: convertToMB(memUsage.heapUsed),
    external: convertToMB(memUsage.external), // 这个是Nodejs 引用的C++对象占用的内存
    freeMemory: convertToMB(os.freemem()), // 可以看到操作系统有多少空闲内存
  };
}

function systemMemory() {
  const totalMemory = os.totalmem();
  const freeMemory = os.freemem();
  const usedMemory = totalMemory - freeMemory;
  const memoryUsagePercentage = ((usedMemory / totalMemory) * 100).toFixed(2);
  return {
    totalMemory: convertToMB(totalMemory),
    freeMemory: convertToMB(freeMemory),
    usedMemory: convertToMB(usedMemory),
    memoryUsagePercentage: memoryUsagePercentage + "%",
  };
}

export const GET = async (req: NextRequest) => {
  // 获取CPU核心信息
  const cpus = os.cpus();

  // 计算总的用户时间和系统时间（不包括空闲时间和nice时间）
  let totalUser = 0;
  let totalSystem = 0;
  cpus.forEach((cpu) => {
    totalUser += cpu.times.user;
    totalSystem += cpu.times.sys;
  });

  // 计算平均CPU占用率（用户时间+系统时间）/（总的CPU时间）* CPU核心数 * 100%
  // 注意：这个计算给出的是自系统启动以来的平均占用率，并非实时占用率
//   const totalCpuTime = cpus.length * (totalUser + totalSystem);
//   const averageCpuUsage = ((totalUser + totalSystem) / totalCpuTime) * 100;

//   console.log("CPU核心数量:", cpus.length);
//   console.log("每个核心的用户时间、系统时间等:", cpus);
//   console.log("平均CPU占用率（自启动以来）:", averageCpuUsage.toFixed(2) + "%");
  //   return NextResponse.json(formatMemoryUsageInMB());
  return NextResponse.json(systemMemory());
};
export const dynamic = "force-dynamic";
